<template>
  <div class="vacation-balance-container">
    <div class="page-header">
      <div class="header-left">
      查询部门
        <el-cascader
          style="width: 230px"
          :options="cascaderOptions"
          v-model="selectedOptions"
          placeholder="请选择筛选条件"
          @change="handleCascaderChange"
          :props="{ checkStrictly: true, expandTrigger: 'click' }"
        ></el-cascader>
      </div>
      <div>
        <el-button type="primary" @click="yearVacationBon"> 年假余额初始 </el-button>
        <el-button type="primary" @click="vacationAllhandle">假期批量处理</el-button>
        <!-- <el-button type="primary" @click="handleExport">导出</el-button> -->
      </div>
    </div>

    <!-- 当没有数据时显示提示信息 -->
    <div v-if="filteredBalanceList.length === 0 && !loading" class="empty-message">
      <p>没有找到假期余额数据。</p>
    </div>

    <div class="table-container">
      <!-- Loading 组件 -->
      <div
        v-if="loading"
        class="loading-overlay"
        v-loading="loading"
        element-loading-text="加载中..."
      ></div>
      <el-table
        v-if="vacationRules.length > 0 && filteredBalanceList.length > 0"
        :data="filteredBalanceList || []"
        border
        style="width: 100%"
         height="75vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="姓名" width="200" />
        <el-table-column prop="department" label="部门" />
        <el-table-column prop="joinDate" label="入职时间" />

        <el-table-column prop="joinDate" label="入职时间"> </el-table-column>

        <template v-for="leave in vacationRules" :key="leave.leaveCode">
          <el-table-column
            :prop="leave.leaveCode"
            :label="`${leave.leaveName}（${leaveViewUnitMap[leave.leaveViewUnit]}）`"
          >
            <template #default="{ row }">
              <span v-if="leave.leaveName == '年假'||leave.leaveName == '例假'">
                {{ row[`${leave.leaveName}${leave.leave_code}`] }}
              </span>
              <span v-else class="unlimited" @click="handleEditBalance(leave, row)">
                {{ row[`${leave.leaveName}${leave.leave_code}`] }}
              </span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="
        isjiaqiguize
          ? '请在假期规则中添加该员工'
          : `${currentField.label} 假期总余额为 ${currentField.quotaNum} ${
              leaveViewUnitMap[currentField.unit]
            }`
      "
      width="650px"
      :close-on-click-modal="false"
      class="balance-dialog"
     >
      <div style="display: flex; justify-content: space-around">
        <div>
          <el-form
            ref="formRef"
            :disabled="isjiaqiguize"
            :model="fors"
            :rules="rules"
            label-width="130px"
            class="balance-form"
          >
            <el-form-item label="周期选择" prop="quota_cycle">
              <el-date-picker
                v-model="fors.quota_cycle"
                :value-format="valueformat"
                :type="selectzhouqi"
                placeholder="请选择假期周期"
                :default-value="new Date()"
                :clearable="false"
              />
            </el-form-item>

            <el-form-item label="增加或减少余额" prop="quota_num" class="balance-item">
              <div class="balance-input-group">
                <el-button @click="addjiaqi">+</el-button>
                <el-input-number
                  v-model="formData.number"
                  :controls="false"
                  class="value-input"
                  style="width: 60px"
                />
                <el-button @click="offjiaqi">-</el-button>
                <span class="unit">{{ leaveViewUnitMap[currentField.unit] }}</span>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-table :data="vacationlogdata" style="width: 100%" height="180">
            <el-table-column label="假期周期">
              <template #default="scope">
                <span>{{ deteqiege(scope.row.years) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="假期余额">
              <template #default="scope">
                <span>{{ scope.row.numbers }} 天</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="isjiaqiguize"
            @click="handleSubmit(formRef)"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="vacationDialogVisible" title="假期批量处理" width="500" center>
      <div class="block">
        <el-form
          ref="formRefdata"
          style="max-width: 600px"
          :model="fors"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="选中人员有：">
            <div style="margin-bottom: 20px">
              <el-scrollbar height="80px">
              <span v-for="item in selectables" style="margin-right: 8px">
                {{ item.username }}
              </span>
              <span style="font-weight: 600;">共{{ selectables.length }}人</span>
              </el-scrollbar>
              
            </div>
          </el-form-item>

          <el-form-item label="假期类型">
            <el-radio-group v-model="radiovalue">
              <el-radio-button
                v-for="item in balanceTypeList"
                :label="item.leaveName"
                :value="item.leave_code"
              />
            </el-radio-group>
          </el-form-item>

          <el-form-item label="周期选择" prop="quota_cycle">
            <el-date-picker
              v-model="fors.quota_cycle"
              :value-format="valueformat"
              :type="selectzhouqi"
              placeholder="Pick a date"
              :default-value="new Date()"
            />
          </el-form-item>

          <el-form-item label="假期余额" prop="quota_num">
            <el-input-number
              v-model="fors.quota_num"
              :controls="false"
              class="value-input"
            />
            <span style="margin-left: 8px"> 天</span>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="vacationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(formRefdata)"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div style="display: flex; align-items: center">
      <div class="demo-pagination-block" v-if="filteredBalanceList.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :size="size"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalpage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useVacationBalanceStore } from "@/stores/vacationBalance";
import { ElMessage } from "element-plus";
import { getDepartmentList } from "@/api/department";
import { yearVacationbone } from "@/api/vacation";
import type { ComponentSize, FormRules } from "element-plus";
import { getVacationlog } from "@/api/vacation";

const balanceStore = useVacationBalanceStore();
const vacationRules = ref([]);
const loading = ref(true);

const selectzhouqi = ref("year");
const valueformat = ref("YYYY");
const formRefdata = ref();

const rules = reactive<FormRules>({
  quota_cycle: [{ required: true, message: "请选择周期" }],
  quota_num: [
    { required: true, message: "请填写假期余额" },
    { type: "number", message: "为数字" },
  ],
});

const deptid = ref("");

//分页
//当前叶
const currentPage = ref(1);
//一页多少个
const pageSize = ref(10);
const size = ref<ComponentSize>("default");
const background = ref(false);
//总页数
const totalpage = ref();
const handleSizeChange = async (val: number) => {
  pageSize.value = val;
  getlist();
};
const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  getlist();
};

const balanceTypeList = ref([]);

//批量处理假期选择
const radiovalue = ref();

//批量处理form表单
const fors = reactive({
  userid: [],
  quota_cycle: "",
  quota_num: 0,
  leave_code: "",
});

//年假期初始化
const yearVacationBon = async () => {
  try {
    const res = await yearVacationbone();
    if (res.code == "200") {
      ElMessage.success("年假余额初始化成功");
    } else {
      ElMessage.error("年假余额初始化失败");
    }
  } catch (error) {
    console.error("年假余额初始化失败");
  }
};

// 批量处理提交按钮
const submitForm = async (formEl: any) => {
  if (!formEl) return;

  try {
    formEl.validate(async (valid: any) => {
      if (selectables.value.length == 0) {
        ElMessage.warning("人员不能为空");
        return;
      }
      if (fors.quota_num < 0) {
        ElMessage.warning("假期余额不能为负数");
        return;
      }

      if (valid) {
        fors.leave_code = radiovalue.value;
        fors.userid = [];

        selectables.value.forEach((element) => {
          fors.userid.push(element.userid);
        });
        fors.quota_cycle = Number(fors.quota_cycle);
        // 调用更新接口
        const success = await balanceStore.updateBalance(fors);
        if (success) {
          vacationDialogVisible.value = false;
        }
      } else {
        console.log("error submit!");
      }
    });
  } catch (error) {
    console.error(error);
  }
};

// 监听假期选择改变假期周期格式
watch(radiovalue, (newval, olldval) => {
  if (newval == LJcode.value) {
    valueformat.value = "YYYYMM";
    selectzhouqi.value = "month";
  } else {
    valueformat.value = "YYYY";
    selectzhouqi.value = "year";
  }
});

//假期批量处理弹框
const vacationDialogVisible = ref(false);

//假期批量处理添加按钮
const vacationAllhandle = () => {
  radiovalue.value = SHcode.value;
  Object.assign(fors, {
    userid: [],
    quota_cycle: "",
    quota_num: null,
    leava_code: "",
  });
  vacationDialogVisible.value = true;
};

//选中的人员
const selectables = ref([]);

const handleSelectionChange = (val: any) => {
  selectables.value = val;
};

// 请假时长单位映射
const leaveViewUnitMap = {
  day: "天",
  halfDay: "天",
  hour: "小时",
};

const addjiaqi = () => {
  formData.number = Number(formData.number) + 1;
};

const offjiaqi = () => {
  formData.number = Number(formData.number) - 1;
};

// 过滤后的列表数据
const filteredBalanceList = computed(() => {
  return balanceStore.balanceList;
});

// 筛选框！！！！！
const cascaderOptions = ref([]); //遍历数据
// 初始化响应式变量
const selectedOptions = ref([]); // 存储用户选择的结果

// 筛选定义改变事件处理器
const handleCascaderChange = async (value: any) => {
  if (value) {
    deptid.value = value[value.length - 1].toString().split("-")[0];
    getlist();
  }
};

// 定义转换函数
function transformDataForCascader(data) {
  return data.map((item) => ({
    value: `${item.selfid}-${item.dept_name}`,
    label: item.dept_name,
    children:
      item.childs && item.childs.length ? transformDataForCascader(item.childs) : null,
  }));
}

const SHcode = ref("");
const LJcode = ref("");

const getlist = async (val?: any) => {
  if (val) {
    loading.value = true;
    const resda = await getDepartmentList();
    if (resda.code == "200") {
      deptid.value = resda.data.info_list[0].selfid;
      cascaderOptions.value = transformDataForCascader(resda.data.info_list);
      selectedOptions.value = [];
      selectedOptions.value.push(
        `${resda.data.info_list[0].selfid}-${resda.data.info_list[0].dept_name}`
      );
    } else {
      console.error("部门获取失败");
    }
  }

  await balanceStore.fetchBalanceList({
    dept_id: deptid.value,
    pagesize: currentPage.value,
    pagenum: pageSize.value,
  });

  if (balanceStore.balanceList.length > 0) {
    balanceTypeList.value = balanceStore.balanceList[0].holidaylist.filter((ite) => {
      if (ite.leaveName == "年假"||ite.leaveName == "例假") {
        return false
      }else{
        return true
      }
    });
    SHcode.value = balanceStore.balanceList[0].holidaylist[0].leave_code;
    LJcode.value = balanceStore.balanceList[0].holidaylist[2].leave_code;
    radiovalue.value = balanceStore.balanceList[0].holidaylist[0].leave_code;
    vacationRules.value = balanceStore.balanceList[0].holidaylist;
    totalpage.value = balanceStore.balanceList[0].count;
  }
  loading.value = false;
};

// 初始化数据
onMounted(() => {
  getlist(true);
});

// 弹窗相关
const dialogVisible = ref(false);
const formRef = ref();
const formData = reactive({
  number: 1,
});

// 当前编辑的字段信息
const currentField = reactive({
  key: "",
  label: "",
  unit: "",
  row: null as any,
});

const isjiaqiguize = ref(false);

const transformvacationlog = (data: { quota_cycle: any; quota_num: any }[]) =>
  data.map(({ quota_cycle, quota_num }) => ({
    years: quota_cycle,
    numbers: quota_num,
  }));

const deteqiege = (val: {
  toString: () => {
    (): any;
    new (): any;
    length: number;
    slice: { (arg0: number, arg1: number): string; new (): any };
  };
}) => {
  let tate = "";
  let tates = "";
  let conute = "";
  if (val.toString().length == 4) {
    tate = val.toString().slice(0, 4);
    conute = `${tate}年`;
  } else {
    tate = val.toString().slice(0, 4);
    tates = val.toString().slice(4, val.toString().length);
    conute = `${tate}年${tates}月`;
  }
  return conute;
};

const vacationlogdata = ref();

const vacationlog = async (leave_code: any, userid: any) => {
  const res = await getVacationlog({
    leave_code: leave_code,
    userid: userid,
  });

  vacationlogdata.value = transformvacationlog(res.data) || [];
};

// 处理点击修改余额
const handleEditBalance = (holidayData: any, row: any) => {
  vacationlog(holidayData.leave_code, row.userid);

  fors.quota_cycle = "";

  if (holidayData.leave_code == "LHCODE") {
    valueformat.value = "YYYYMM";
    selectzhouqi.value = "month";
  } else {
    valueformat.value = "YYYY";
    selectzhouqi.value = "year";
  }

  currentField.label = row.username;
  currentField.unit = holidayData.leaveViewUnit;
  currentField.leave_code = holidayData.leave_code;
  currentField.userid = row.userid;
  currentField.row = row;
  currentField.quotaNum = row[`${holidayData.leaveName}${holidayData.leave_code}`];
  currentField.leaveViewUnit = holidayData.leaveViewUnit;
  // 重置表单
  formData.number = row[`${holidayData.leaveName}${holidayData.leave_code}`];

  dialogVisible.value = true;
};

// 提交修改
const handleSubmit = async (formEl: any) => {
  if (!formRef.value) return;

  try {
    formEl.validate(async (valid: any) => {
      if (valid) {
        // 构造请求参数
        const userids = [];
        userids.push(currentField.row.userid);
        const params = {
          userid: userids,
          leave_code: currentField.leave_code,
          quota_num: formData.number,
          quota_cycle: Number(fors.quota_cycle),
        };
        // 调用更新接口
        const success = await balanceStore.updateBalance(params);
        if (success) {
          await balanceStore.fetchBalanceList({
            dept_id: deptid.value,
            pagesize: currentPage.value,
            pagenum: pageSize.value,
          });
          dialogVisible.value = false;
        }
      } else {
        console.error("表单未填写完整");
      }
    });
  } catch (error) {
    console.error(error);
  }

  // if (fors.quota_cycle == "") {
  //   ElMessage.warning("请选择假期周期");
  //   return;
  // }
};
</script>

<style lang="scss" scoped>
.vacation-balance-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  min-height: 400px !important;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .empty-message {
    text-align: center;
    color: #999;
    margin: 20px 0;
  }

  .table-container {
    position: relative;
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8); /* 半透明背景 */
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    width: 100%;
    z-index: 10; /* 确保在表格上方 */
  }
}

.unit {
  margin-left: 8px;
  color: #909399;
}

.balance-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-dialog__close {
      font-size: 18px;
      color: #909399;
    }
  }

  :deep(.el-dialog__body) {
    padding: 24px 20px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid #dcdfe6;
  }
}

.balance-form {
  :deep(.el-form-item) {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .el-form-item__label {
      font-weight: normal;
      padding-right: 12px;
      white-space: nowrap;
      height: 32px;
      line-height: 32px;
      color: #606266;

      &::before {
        margin-right: 4px;
        color: #f56c6c;
      }
    }
  }

  .balance-input-group {
    display: flex;
    align-items: center;
    gap: 12px;
    height: 32px;
  }

  .type-select {
    width: 100px;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      height: 32px;
    }
  }

  .value-input {
    width: 120px;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      height: 32px;
    }

    :deep(.el-input__inner) {
      text-align: left;
      padding-left: 12px;
      height: 32px;
      line-height: 32px;
    }
  }

  .unit {
    color: #606266;
    margin-left: 4px;
    line-height: 32px;
  }

  :deep(.el-textarea__inner) {
    font-family: inherit;
    padding: 8px 12px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    min-height: 80px;

    &::placeholder {
      color: #c0c4cc;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .el-button {
    padding: 8px 20px;
    min-width: 80px;
    height: 32px;
    line-height: 1;
  }
}

.unlimited:hover {
  text-decoration: underline;
  color: #409eff;
  cursor: pointer;
}
</style>
